<template>
  <div class="app-container">

    <!--搜索项-->
    <div id="foldDiv">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="股票编码" prop="stockCode">
          <el-input v-model="queryParams.stockCode" @clear="handleQuery" @blur="handleQuery" clearable
                    @keyup.enter.native="handleQuery"/>
        </el-form-item>
        <el-form-item label="分组" prop="groupId">
          <el-select :popper-append-to-body="false" popper-class="el-select-popper" v-model="queryParams.groupId"
                     clearable @change="getList">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-loading" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          <el-button type="primary" icon="el-icon-back" size="mini" @click="back">返回</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div v-show="showTable">
      <!--操作按钮-->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">
            批量删除
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-sunny" size="mini" @click="handleGenerateMyKLine">我的K线
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" icon="el-icon-sunny" size="mini" @click="handleGenerateKLine">EchartsK线
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="danger" icon="el-icon-loading" size="mini" @click="handleKLineCharts">KLineCharts
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <!--表格-->
      <el-table id="tableDiv" :height="tableHeight" v-loading="loading" border :data="myAttentionList"
                @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="股票编码" align="center" prop="stockCode"/>
        <el-table-column label="股票名称" align="center" prop="stockName"/>
        <el-table-column label="分组" align="center" prop="groupId">
          <template slot-scope="scope">
            <dict-tag :options="options" :value="scope.row.groupId"/>
          </template>
        </el-table-column>
        <el-table-column label="排序" align="center" prop="sortNum"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改
            </el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" @pagination="getList" :total="total" :page.sync="queryParams.pageNum"
                  :limit.sync="queryParams.pageSize"/>
    </div>

    <!-- 新增修改弹窗组件-->
    <addOrUpdate v-if="addOrUpdateParam.open" ref="addOrUpdateDialog" :addOrUpdateParam="addOrUpdateParam"
                 @getList="getList"/>

    <!--我的K线图-->
    <div v-if="isShowMyKLine">
      <template v-for="(item) in stockCodeKLine">
        <el-card style="margin-top:20px">
          <div :id="'d'+item.split('_')[0]" style="width: 100%;height: 600px"></div>
        </el-card>
      </template>
    </div>

    <!--K线图-->
    <div v-if="isShowKLine">
      <template v-for="(item) in stockCodeKLine">
        <el-card style="margin-top:20px">
          <div :id="'d'+item.split('_')[0]" style="width: 100%;height: 600px"></div>
        </el-card>
      </template>
    </div>

    <!--kLineChart-->
    <div v-if="showKLineChartsFlag">
      <template v-for="(item, index) in stockCodeKLine">
        <el-card style="margin-top:20px">
          <ShowKLineCharts :chart-div-id="'d'+item.split('_')[0]" :stock-code="item.split('_')[0]"
                           :stock-name="item.split('_')[1]"></ShowKLineCharts>
        </el-card>
      </template>
    </div>

    <!-- 滑动到页面底部会看见-->
    <el-backtop>返回</el-backtop>

  </div>
</template>

<script>
import {
  listMyAttention,
  delMyAttention
} from '@/api/eye/myAttention'
import {listStockGroupOption} from '@/api/eye/stockGroup'
import AddOrUpdate from './addOrUpdate.vue'
import Vue from 'vue'
import ElementResizeDetectorMaker from 'element-resize-detector'

Vue.prototype.$erd = ElementResizeDetectorMaker()

import {
  getHistoryPriceByStockCode
} from '@/api/eye/stockPrice'
import {renderKLine} from '@/api/eye/kline'
import {initDragonKLine} from '@/api/eye/myKLine.js'
import Sortable from 'sortablejs'
import {batchUpdateMyAttention} from '@/api/eye/myAttention'
import {getStock} from '@/api/eye/stock'
import ShowKLineCharts from '@/views/eye/components/ShowKLineCharts'

export default {
  name: 'MyAttention',
  components: {AddOrUpdate, ShowKLineCharts},
  data() {
    return {
      tableHeight: 200,
      options: [],
      addOrUpdateParam: {
        open: false // 是否显示弹出层
      },
      showTable: true,
      // 展示我的K线
      isShowMyKLine: false,
      // K线图是否显示
      isShowKLine: false,
      showKLineChartsFlag: false,
      // 遮罩层
      loading: true,
      // 选中IDS
      ids: [],
      // 股票编码K线图
      stockCodeKLine: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 我的关注表格数据
      myAttentionList: [],
      // 查询参数
      queryParams: {
        pageNum: 1, pageSize: 50, stockCode: null, groupId: null, groupName: null
      },
      // 表单校验
      rules: {}
    }
  },
  created() {
    this.listStockGroupOption()
    this.getList()
  },
  mounted() {
    this.initSortable()
    this.getTableMaxHeight()
    let _this = this
    window.onresize = function () {
      console.log('onresize 我的关注')
      //页面改变重新自适应高度
      _this.getTableMaxHeight()
    }
    this.$erd.listenTo(document.getElementById('foldDiv'), () => {
      console.log('listen 我的关注')
      _this.getTableMaxHeight()
    })
  },
  methods: {
    initSortable() {
      //将el-table变为可拖拽的
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const t = this
      Sortable.create(tbody, {
        onEnd({newIndex, oldIndex}) {

          let dragBeforeArray = JSON.parse(JSON.stringify(t.myAttentionList))
          let dragBeforeSortNum = dragBeforeArray.map(item => item.sortNum)

          let dragAfterArray = []
          dragBeforeArray.splice(newIndex, 0, dragBeforeArray.splice(oldIndex, 1)[0])

          dragAfterArray = JSON.parse(JSON.stringify(dragBeforeArray))

          t.myAttentionList = []
          t.$nextTick(function () {
            t.myAttentionList = dragAfterArray
          })

          let update = []
          for (let i = 0; i < dragAfterArray.length; i++) {
            dragAfterArray[i].sortNum = dragBeforeSortNum[i]
            update.push({id: dragAfterArray[i].id, sortNum: dragBeforeSortNum[i]})
          }

          batchUpdateMyAttention(update).then(res => {
            t.$modal.msgSuccess(res.msg)
          })

        }
      })
    },
    //获取容器当前高度，重设表格的最大高度
    getTableMaxHeight() {
      this.$nextTick(function () {
        let t = document.querySelector('#tableDiv')
        console.log('我的关注 重置高度')
        // 在别的页面缩放此值为null
        if (t == null) return
        this.tableHeight = window.innerHeight - t.getBoundingClientRect().top - 80
      })
    },
    /** 查询我的关注列表 */
    getList() {
      this.loading = true
      listMyAttention(this.queryParams).then(response => {
        this.myAttentionList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    listStockGroupOption() {
      listStockGroupOption().then(response => {
        response.data.forEach((item) => {
          let o = {}
          o.value = item.id
          o.label = item.name
          o.raw = {listClass: item.classStyle}
          this.options.push(o)
        })
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.isShowKLine = false
      this.isShowMyKLine = false
      this.showKLineChartsFlag = false
      this.showTable = true
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.showTable = true
      this.showKLineChartsFlag = false
      this.isShowKLine = false
      this.isShowMyKLine = false
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 返回table */
    back() {
      this.showTable = true
      this.showKLineChartsFlag = false
      this.isShowKLine = false
      this.isShowMyKLine = false
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.stockCodeKLine = selection.map(item => item.stockCode + '_' + item.stockName)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      console.log('通过v-if调用子组件的添加弹窗')
      this.addOrUpdateParam.open = true
      let add = {groupId: '1'}
      this.$nextTick(() => {
        this.$refs.addOrUpdateDialog.handleAddOrUpdate(add)
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const id = row.id || this.ids
      getStock(id).then(response => {
        console.log('通过v-if调用子组件的添加弹窗')
        this.addOrUpdateParam.open = true
        this.$nextTick(() => {
          this.$refs.addOrUpdateDialog.handleAddOrUpdate(response.data)
        })
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认删除?').then(function () {
        return delMyAttention(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },

    /** 生成我的K线图 */
    handleGenerateMyKLine() {
      this.showTable = false
      this.showKLineChartsFlag = false
      this.isShowMyKLine = true
      this.stockCodeKLine.forEach(item => {
        let code = item.split('_')[0]
        getHistoryPriceByStockCode(code).then(response => {
          initDragonKLine('d' + code, item, response.data.date, response.data.price)
        })
      })
    },
    /** 生成K线图 */
    handleGenerateKLine() {
      this.showTable = false
      this.showKLineChartsFlag = false
      this.isShowKLine = true
      this.stockCodeKLine.forEach(item => {
        let code = item.split('_')[0]
        getHistoryPriceByStockCode(code).then(response => {
          renderKLine('d' + code, item, response.data, 1)
        })
      })
    },
    /** 生成kLineCharts */
    handleKLineCharts() {
      this.showKLineChartsFlag = true
      this.showTable = false
    }
  }
}
</script>

<style lang="scss" scoped>

::v-deep .el-icon-sunny {
  color: #ff0000;
  animation: rotating 1s linear infinite
}

::v-deep .el-icon-plus {
  color: #05ff00;
  animation: rotating 1s linear infinite
}

::v-deep .el-icon-back {
  color: #05ff00;
  animation: rotating 1s cubic-bezier(0.7, -0.05, 1, 0.22) infinite
}

::v-deep .el-table--enable-row-hover .el-table__body tr:hover > td {
  background-color: #f56c6cad !important;
}

.app-container {
  background-color: #f9fafc;
}

.el-select-popper .el-select-dropdown__item:hover {
  background-color: #F56C6C !important;
}

::v-deep .el-select-popper .el-select-dropdown__wrap {
  background-color: #FDE2E2;
  max-height: 800px;
}

.el-card.is-always-shadow {
  box-shadow: 0 12px 9px red;
}

</style>
